package Schema::ResultSet::User;

use Modern::Perl;
use base 'DBIx::Class::ResultSet';
use Crypt::Eksblowfish::Bcrypt qw/bcrypt_hash/;
use MIME::Base64 qw/decode_base64/;

sub by_email {
    my ($self, $email) = @_;

    return $self->find(
        {
            email        => $email,
        },
        {
            columns      => [ qw/ id first_name last_name tz / ],
            result_class => 'DBIx::Class::ResultClass::HashRefInflator',
        },
    );
}

sub check_pwd {
    my ($self, $email, $pwd) = @_;

    my $user = $self->find(
        {
            email        => $email,
        },
        {
            columns      => [ qw/ password salt / ],
            result_class => 'DBIx::Class::ResultClass::HashRefInflator',
        },
    ) or return 0;

    my $salt   = decode_base64($user->{salt});
    my $pwd_db = decode_base64($user->{password});

    $pwd = bcrypt_hash({
        key_nul => 1,
        cost    => 8,
        salt    => $salt,
    }, $pwd);

    return $pwd eq $pwd_db;
}

1;
